package com.meadin.agent.utils;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.meadin.agent.domain.HttpEntitiy;

public class HttpProxy {

	public static HttpEntitiy getProxy(String link) {
		// 代理服务器
		final String proxyHost = "proxy.abuyun.com";
		final Integer proxyPort = 9020;

		// 代理隧道验证信息
		final String proxyUser = "H549681BA0CGPECD";
		final String proxyPass = "23617E0B65C13DDF";

		// 设置HttpHost
		HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");

		// 设置credsProvider
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPass));

		CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

		// 将代理设置到HttpClient中
		AuthCache authCache = new BasicAuthCache();
		authCache.put(proxy, new BasicScheme());

		HttpPost post = new HttpPost(link);

		// localContext
		HttpClientContext localContext = HttpClientContext.create();
		localContext.setAuthCache(authCache);

		post.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36");
		// 请求配置
		RequestConfig config = RequestConfig.custom().setProxy(new HttpHost(proxyHost, proxyPort))
				.setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
		post.setConfig(config);

		HttpEntitiy he = new HttpEntitiy();
		he.setClient(client);
		he.setPost(post);

		return he;
	}
}
